package middleware

import (
	"GoTime/utils"
	"log"
	"net/http"
	"strconv"
	"strings"

	"fmt"

	"github.com/gin-gonic/gin"
)

var WhiteList = []string{"222.174.55.106", "47.114.137.243", "121.40.157.144", "127.0.0.1"}

// VerifyToken 校验token
func VerifyToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			token            string
			school_id        int
			err              error
			institution_code string
		)
		if c.HandlerName() == "jishi/handlers.Login" {
			c.Next()
			return
		}
		fmt.Println(c.HandlerName(), "----------")
		authorization := c.Request.Header.Get("Authorization")
		if authorization == "" {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"code": 201,
				"msg":  "校验码为空",
			})
			return
		}
		tokens := strings.Split(authorization, " ")
		if len(tokens) == 1 {
			token = tokens[0]
		} else if len(tokens) == 2 {
			token = tokens[1]
		}
		if c.Request.Method == "POST" {
			school_id, err = strconv.Atoi(c.PostForm("school_id"))
			if err != nil {
				c.Abort()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			institution_code = c.PostForm("institution_code")
		} else if c.Request.Method == "GET" {
			school_id, err = strconv.Atoi(c.Query("school_id"))
			if err != nil {
				c.Abort()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			institution_code = c.Query("institution_code")
		}
		log.Print("token:", token, "school_id:", school_id, "institution_code:", institution_code)
		ok, err := utils.VerifyToken(token, school_id, institution_code)
		if !ok {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "校验失败，请重新登录"})
			return
		}
		c.Set("school_id", school_id)
		c.Set("institution_code", institution_code)
		c.Next()
	}
}
